;;; bir-split.el --- Split functions for BIR         -*- lexical-binding: t; -*-

;; Copyright (C) 2021  c1-g

;; Author: c1-g <char1iegordon@protonmail.com>
;; Keywords: 

;; This program is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.

;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
;; along with this program.  If not, see <https://www.gnu.org/licenses/>.

;;; Commentary:

;; 

;;; Code:

(require 'org-fc)

(defun bir-split (arg)
  (interactive "P")
  (let* ((file-level-p (org-with-point-at (point-min) (= (org-outline-level) 0)))
         (article-title (if file-level-p
                            (cadar (org-collect-keywords '("TITLE")))
                          (save-excursion (while (org-up-heading-safe))
                                          (nth 4 (org-heading-components)))))
         (article-prop (org-entry-get nil bir-article-property t))
         (article-id (cond (article-prop (progn (string-match org-link-bracket-re article-prop)
                                                (substring-no-properties (match-string 1 article-prop) 3)))
                           (file-level-p (org-with-point-at (point-min) (org-id-get-create)))
                           (t (save-excursion (while (org-up-heading-safe))
                                              (org-id-get-create)))))
         (article (org-link-make-string (concat "id:" article-id) article-title))

         (refs (org-roam-node-refs (org-roam-node-from-id article-id)))

         (split-dir (file-name-as-directory (expand-file-name article-id bir-directory)))
         (count (how-many org-outline-regexp-bol (point-min) (point-max)))
         ids
         split-files
         template)
    (make-directory split-dir t)
    (setq ids (org-map-entries #'org-id-get-create))
    (save-buffer)
    (org-show-all)
    (start-process "bir-split" nil (or (executable-find "gcsplit")
                                       (executable-find "csplit"))
                   "-s" "-z" "-f" (shell-quote-argument split-dir)
                   "-b" (format "%%0%dd.org"
                                (string-width (number-to-string count)))
                   (shell-quote-argument (buffer-file-name))
                   "/^\\*\\+ /" "{*}")
    (setq split-files (directory-files split-dir t directory-files-no-dot-files-regexp))
    (when split-files
      (org-map-entries (lambda ()
                         (org-set-property "CUSTOM_ID" (org-id-get))
                         (org-delete-property "ID")))
      (save-buffer)
      (org-roam-db-update-file))
    (dolist (file split-files)
      (with-temp-buffer
        (org-mode)
        (insert-file-contents file)
        (goto-char (point-min))
        (setq template (org-roam-format-template
                        (string-trim (org-capture-fill-template org-roam-extract-new-file-path))
                        (lambda (key default-val)
                          (let ((fn (intern key))
                                (node-fn (intern (concat "org-roam-node-" key)))
                                (ksym (intern (concat ":" key))))
                            (cond
                             ((fboundp fn)
                              (funcall fn node))
                             ((fboundp node-fn)
                              (funcall node-fn node))
                             (t (let ((r (read-from-minibuffer (format "%s: " key) default-val)))
                                  (plist-put template-info ksym r)
                                  r)))))))
        (write-region (point-min) (point-max) file nil t)
        (org-set-property bir-article-property article)
        (when refs (org-set-property "ROAM_REFS" (concat "cite:&" (car refs))))
        (org-fc-type-topic-init)
        (when (> (org-outline-level) 0)
          (org-schedule '(4))
          (let ((title (nth 4 (org-heading-components)))
                (tags (nth 5 (org-heading-components))))
            (beginning-of-line)
            (kill-line 1)
            (org-roam-end-of-meta-data 'full)
            (insert "#+TITLE: " title "\n")
            (when tags (insert "#+FILETAGS: " tags "\n"))))
        (save-buffer)
        (org-id-add-location (org-id-get) (buffer-file-name))
        (org-roam-db-update-file)))
    ids))

(provide 'bir-split)
;;; bir-split.el ends here
